package com.example.onlinemonitoring.comCenter;

import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.TimeUnit;

import com.example.onlinemonitoring.Util.CRC16;
import com.example.onlinemonitoring.Util.CommPortManager;
import com.example.onlinemonitoring.Util.HexUtil;
import com.example.onlinemonitoring.model.Appdevice;
import com.example.onlinemonitoring.model.Hgbhhistory;
import com.example.onlinemonitoring.model.Hgbhsensor;
import com.example.onlinemonitoring.serviceImpl.HgbhsensorServiceImpl;
import com.example.onlinemonitoring.Util.IEEE754Utils;
import lombok.Data;

import org.springframework.context.annotation.Scope;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * freemarker填充
 */
@Service("hgbhCom")
@Scope("prototype")
public class HgbhCom extends CommPortManager {
    @Autowired
    private HgbhsensorServiceImpl hgbhserviceimpl;

    public void receiveDatas(String str) {
        str = str.toUpperCase();
        setText(str);
        String addrstr = str.substring(0, 2);
        Integer addrint = parseHex4(addrstr);
        reSend[addrindex] = 0;
        if (currcmd == 1) {
            addrindex++;
        }
        String cmdstr = str.substring(2, 4);
        Integer cmdint = parseHex4(cmdstr);
        byte[] carr = HexUtil.hexString2Bytes(str);
        Date dt = new Date();
        Hgbhsensor hgbh = new Hgbhsensor();
        hgbh.setStationid(ad.getStationid());
        hgbh.setDevicegroup(ad.getDevicegroup());
        hgbh.setDeviceaddr(addrint);
        Hgbhsensor record = hgbhserviceimpl.getModel(hgbh);
        hgbh.setLastdatatime(dt);
        switch (cmdint) {
            case 2://freemarker填充                
                // hgbh.setLastarclight1(parseHex4(str.substring(,)));// 主机弧光1 
                // hgbh.setLastarclight2(parseHex4(str.substring(,)));// 主机弧光2 
                // hgbh.setLastarclight3(parseHex4(str.substring(,)));// 主机弧光3 
                // hgbh.setLastarclight4(parseHex4(str.substring(,)));// 主机弧光4 
                // hgbh.setLastarclight5(parseHex4(str.substring(,)));// 主机弧光5 
                // hgbh.setLastarclight6(parseHex4(str.substring(,)));// 主机弧光6 
                // hgbh.setLastarclight7(parseHex4(str.substring(,)));// 主机弧光7 
                // hgbh.setLastarclight8(parseHex4(str.substring(,)));// 主机弧光8 
                // hgbh.setLastarclight9(parseHex4(str.substring(,)));// 主机弧光9 
                // hgbh.setLastarclight10(parseHex4(str.substring(,)));// 主机弧光10
                // hgbh.setLastarclight11(parseHex4(str.substring(,)));// 主机弧光11
                // hgbh.setLastarclight12(parseHex4(str.substring(,)));// 主机弧光12
                // hgbh.setLastarclight13(parseHex4(str.substring(,)));// 主机弧光13
                // hgbh.setLastarclight14(parseHex4(str.substring(,)));// 主机弧光14
                // hgbh.setLastarclight15(parseHex4(str.substring(,)));// 主机弧光15
                // hgbh.setLastarclight16(parseHex4(str.substring(,)));// 主机弧光16
                // hgbh.setLastarclight17(parseHex4(str.substring(,)));// 主机弧光17
                // hgbh.setLastarclight18(parseHex4(str.substring(,)));// 主机弧光18
                // hgbh.setLastarclight19(parseHex4(str.substring(,)));// 主机弧光19
                // hgbh.setLastarclight20(parseHex4(str.substring(,)));// 主机弧光20
                // hgbh.setLastarclight21(parseHex4(str.substring(,)));// 主机弧光21
                // hgbh.setLastarclight22(parseHex4(str.substring(,)));// 主机弧光22
                // hgbh.setLastarclight23(parseHex4(str.substring(,)));// 主机弧光23
                // hgbh.setLastarclight24(parseHex4(str.substring(,)));// 主机弧光24
                // hgbh.setLasttimingsignalstatus(parseHex4(str.substring(,)));// 主机故障出口
                // hgbh.setLasttimeservicestatus(parseHex4(str.substring(,)));// 主机报警出口
                // hgbh.setLastinput1(parseHex4(str.substring(,)));// 主机快速出口1
                // hgbh.setLastinput2(parseHex4(str.substring(,)));// 主机快速出口2
                hgbh.setLastarclight1(carr[3] >> 0 & 1);// 主机弧光1 
                hgbh.setLastarclight2(carr[3] >> 1 & 1);// 主机弧光2 
                hgbh.setLastarclight3(carr[3] >> 2 & 1);// 主机弧光3 
                hgbh.setLastarclight4(carr[3] >> 3 & 1);// 主机弧光4 
                hgbh.setLastarclight5(carr[3] >> 4 & 1);// 主机弧光5 
                hgbh.setLastarclight6(carr[3] >> 5 & 1);// 主机弧光6 
                hgbh.setLastarclight7(carr[3] >> 6 & 1);// 主机弧光7 
                hgbh.setLastarclight8(carr[3] >> 7 & 1);// 主机弧光8 
                hgbh.setLastarclight9(carr[4] >> 0 & 1);// 主机弧光9 
                hgbh.setLastarclight10(carr[4] >> 1 & 1);// 主机弧光10
                hgbh.setLastarclight11(carr[4] >> 2 & 1);// 主机弧光11
                hgbh.setLastarclight12(carr[4] >> 3 & 1);// 主机弧光12
                hgbh.setLastarclight13(carr[4] >> 4 & 1);// 主机弧光13
                hgbh.setLastarclight14(carr[4] >> 5 & 1);// 主机弧光14
                hgbh.setLastarclight15(carr[4] >> 6 & 1);// 主机弧光15
                hgbh.setLastarclight16(carr[4] >> 7 & 1);// 主机弧光16
                hgbh.setLastarclight17(carr[5] >> 0 & 1);// 主机弧光17
                hgbh.setLastarclight18(carr[5] >> 1 & 1);// 主机弧光18
                hgbh.setLastarclight19(carr[5] >> 2 & 1);// 主机弧光19
                hgbh.setLastarclight20(carr[5] >> 3 & 1);// 主机弧光20
                hgbh.setLastarclight21(carr[5] >> 4 & 1);// 主机弧光21
                hgbh.setLastarclight22(carr[5] >> 5 & 1);// 主机弧光22
                hgbh.setLastarclight23(carr[5] >> 6 & 1);// 主机弧光23
                hgbh.setLastarclight24(carr[5] >> 7 & 1);// 主机弧光24
                break;
            case 1://freemarker填充    
                hgbh.setLasttimingsignalstatus(carr[3] >> 0 & 1);// 主机故障出口
                hgbh.setLasttimeservicestatus(carr[3] >> 1 & 1);// 主机报警出口
                hgbh.setLastinput1(carr[3] >> 2 & 1);// 主机快速出口1
                hgbh.setLastinput2(carr[3] >> 3 & 1);// 主机快速出口2
                String alm = "";
                hgbh.setLastalarmlevel(0);
                hgbh.setLastalarmmessage("");
                if(hgbh.getLasttimingsignalstatus() == 1){//freemarker填充
                    alm+="主机故障,"; //freemarker填充
                    hgbh.setLastalarmlevel(2);
                    hgbh.setLastalarmmessage(alm);
                }
                if(hgbh.getLasttimeservicestatus() == 1){//freemarker填充
                    alm+="主机报警,"; //freemarker填充
                    hgbh.setLastalarmlevel(2);
                    hgbh.setLastalarmmessage(alm);
                }
                if(hgbh.getLastinput1() == 1){//freemarker填充
                    alm+="主机快速出口1,"; //freemarker填充
                    hgbh.setLastalarmlevel(2);
                    hgbh.setLastalarmmessage(alm);
                }
                if(hgbh.getLastinput2() == 1){//freemarker填充
                    alm+="主机快速出口2,"; //freemarker填充
                    hgbh.setLastalarmlevel(2);
                    hgbh.setLastalarmmessage(alm);
                }
                if(alm.length() == 0){
                    GetNormalAlarm("弧光保护"+record.getDeviceaddr(),record.getDevicegroup(), record.getDeviceaddr(),0, record.getPointname(), "", false);//freemarker填充
                    setText("无报警");
                }else{
                    GetNormalAlarm("弧光保护"+record.getDeviceaddr(),record.getDevicegroup(), record.getDeviceaddr(),0, record.getPointname(), alm, true);//freemarker填充
                    setText(alm);
                }
                break;
            case 4: //freemarker填充
                int startindex = 6;//freemarker填充
                // hgbh.setLastia1(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机1号IA
                // hgbh.setLastib1(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机1号IB
                // hgbh.setLastic1(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机1号IC
                // hgbh.setLastia2(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机2号IA
                // hgbh.setLastib2(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机2号IB
                // hgbh.setLastic2(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机2号IC
                // hgbh.setLastia3(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机3号IA
                // hgbh.setLastib3(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机3号IB
                // hgbh.setLastic3(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机3号IC
                // hgbh.setLastia4(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机4号IA
                // hgbh.setLastib4(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机4号IB
                // hgbh.setLastic4(parseHex4(str.substring(startindex, startindex+=4)) * 1.0f);// 主机4号IC
                hgbh.setLastia1(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机1号IA
                hgbh.setLastib1(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机1号IB
                hgbh.setLastic1(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机1号IC
                hgbh.setLastia2(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机2号IA
                hgbh.setLastib2(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机2号IB
                hgbh.setLastic2(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机2号IC
                hgbh.setLastia3(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机3号IA
                hgbh.setLastib3(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机3号IB
                hgbh.setLastic3(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机3号IC
                hgbh.setLastia4(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机4号IA
                hgbh.setLastib4(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机4号IB
                hgbh.setLastic4(IEEE754Utils.strbytesToSingleTurn(str.substring(startindex, startindex+=8)).floatValue() * 1.0f);// 主机4号IC
                hgbh.setLastcommunicationstatus(0);
                hgbh.setLasthisdatatime(addHistory(hgbh));
                setText("设备返回数据： 站点号：1 监测点" + addrint);
                setText("主机1号IA" + hgbh.getLastia1());
                setText("主机1号IB" + hgbh.getLastib1());
                setText("主机1号IC" + hgbh.getLastic1());
                setText("主机2号IA" + hgbh.getLastia2());
                setText("主机2号IB" + hgbh.getLastib2());
                setText("主机2号IC" + hgbh.getLastic2());
                setText("主机3号IA" + hgbh.getLastia3());
                setText("主机3号IB" + hgbh.getLastib3());
                setText("主机3号IC" + hgbh.getLastic3());
                setText("主机4号IA" + hgbh.getLastia4());
                setText("主机4号IB" + hgbh.getLastib4());
                setText("主机4号IC" + hgbh.getLastic4());
                break;
            default:
                break;
        }
        hgbhserviceimpl.Update(hgbh, false);
    }
    private Date addHistory(Hgbhsensor sensor) {
        sensor = hgbhserviceimpl.getModel(sensor);
        if (sensor != null) {
            if (sensor.getLasthisdatatime() == null) {
                add(sensor);
                return new Date();
            } else {
                long lasttime = 0;
                long nowtime = 0;
                try {
                    lasttime = HexUtil.todate(sensor.getLasthisdatatime()).getTime();
                    nowtime = HexUtil.todate(new Date()).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                int timersp = 60000;
                if (sensor.getLastalarmlevel() != 0) {
                    timersp = ad.getHisalarmtimersp()*1000;
                } else {
                    timersp = ad.getHistimersp()*1000;
                }
                if (lasttime + timersp < nowtime) {
                    add(sensor);
                    return new Date();
                }
            }
        }
        return null;
    }
    private void add(Hgbhsensor sensor) {
        Hgbhhistory his = new Hgbhhistory();
        his.setStationid(sensor.getStationid());
        his.setDevicegroup(sensor.getDevicegroup());
        his.setDeviceaddr(sensor.getDeviceaddr());
        his.setAlarmlevel(sensor.getLastalarmlevel());
        his.setAlarmmessage(sensor.getLastalarmmessage());
        his.setDatatime(sensor.getLastdatatime());
        his.setPointname(sensor.getPointname());

        //需要添加自己定义的属性
        //  todo
        his.setIa1(sensor.getLastia1());
        his.setIb1(sensor.getLastib1());
        his.setIc1(sensor.getLastic1());
        his.setIa2(sensor.getLastia2());
        his.setIb2(sensor.getLastib2());
        his.setIc2(sensor.getLastic2());
        his.setIa3(sensor.getLastia3());
        his.setIb3(sensor.getLastib3());
        his.setIc3(sensor.getLastic3());
        his.setIa4(sensor.getLastia4());
        his.setIb4(sensor.getLastib4());
        his.setIc4(sensor.getLastic4());
        his.setArclight1(sensor.getLastarclight1());
        his.setArclight2(sensor.getLastarclight2());
        his.setArclight3(sensor.getLastarclight3());
        his.setArclight4(sensor.getLastarclight4());
        his.setArclight5(sensor.getLastarclight5());
        his.setArclight6(sensor.getLastarclight6());
        his.setArclight7(sensor.getLastarclight7());
        his.setArclight8(sensor.getLastarclight8());
        his.setArclight9(sensor.getLastarclight9());
        his.setArclight10(sensor.getLastarclight10());
        his.setArclight11(sensor.getLastarclight11());
        his.setArclight12(sensor.getLastarclight12());
        his.setArclight13(sensor.getLastarclight13());
        his.setArclight14(sensor.getLastarclight14());
        his.setArclight15(sensor.getLastarclight15());
        his.setArclight16(sensor.getLastarclight16());
        his.setArclight17(sensor.getLastarclight17());
        his.setArclight18(sensor.getLastarclight18());
        his.setArclight19(sensor.getLastarclight19());
        his.setArclight20(sensor.getLastarclight20());
        his.setArclight21(sensor.getLastarclight21());
        his.setArclight22(sensor.getLastarclight22());
        his.setArclight23(sensor.getLastarclight23());
        his.setArclight24(sensor.getLastarclight24());
        his.setTimingsignalstatus(sensor.getLasttimingsignalstatus());
        his.setTimeservicestatus(sensor.getLasttimeservicestatus());
        his.setInput1(sensor.getLastinput1());
        his.setInput2(sensor.getLastinput2());
        hgbhserviceimpl.Add(his);
    }

    @Async("threadPool")
    public void startSendThread(Appdevice Appdevice) throws Exception {
        String cmd[] = new String[3];
        cmd[0] = "%s0400000018";// 遥信  freemarker填充
        cmd[1] = "%s0200280018";// 遥测  freemarker填充
        cmd[2] = "%s010000000C";// 遥控  freemarker填充
        checkType = "crc16";
        issend.put(Thread.currentThread().getId(), true);
        String cstr = "";
        int timeoutsp = (int) Math.round(Appdevice.getTimeoutsp() * 1000);
        timersp = (int) Math.round(Appdevice.getTimersp() * 1000);
        while (issend.get(Thread.currentThread().getId()) != null) {
            rlock.lock();
            try {
                if (isrun) {
                    if (addrindex > Appdevice.getAddrmax() || addrindex < Appdevice.getAddrmin())
                        addrindex = Appdevice.getAddrmin();
                    {
                        cstr = String.format(cmd[currcmd], String.format("%02X", addrindex));
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        Send(cstr);
                        sendCondition.await(timeoutsp,TimeUnit.MILLISECONDS);
                        currcmd++;
                    }
                    {
                        cstr = String.format(cmd[currcmd], String.format("%02X", addrindex));
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        Send(cstr);
                        sendCondition.await(timeoutsp,TimeUnit.MILLISECONDS);
                        currcmd++;
                    }
                    {
                        cstr = String.format(cmd[currcmd], String.format("%02X", addrindex));
                        cstr = cstr + CRC16.calcCrc16(cstr);
                        Send(cstr);
                        sendCondition.await(timeoutsp,TimeUnit.MILLISECONDS);
                        currcmd = 0;
                    }

                    if (reSend[addrindex] > 3) {
                        hgbhserviceimpl.UpdateStatus(ad, addrindex, 1);
                        reSend[addrindex] = 0;
                        addrindex++;
                    }
                    reSend[addrindex]++;
                } else if (rescode != 0) {
                    setText(resmsg[rescode]);
                }
            } catch (Exception e) {
                // TODO: handle exception
            }finally{
                rlock.unlock();
            }
        }
    }
}